<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminAction;
use App\Models\AdminRole;
use App\Models\AdminUser;
use Illuminate\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Requests;
use App\Http\Requests\Admin\Login\LoginRequest;
use App\Http\Controllers\Controller;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\MessageBag;
use Auth,Session,Log;
use App\Models\User;
use App\Commands\OperationLogCommand;

class LoginController extends Controller
{

    public function index()
    {
        return view('admin.login.index');
    }


    public function store(LoginRequest $loginRequest,MessageBag $error)
    {

        if(empty($loginRequest->get('chkCode')) || trim($loginRequest->get('chkCode')) != trim(Session::get('admincaptcha'))){

            $error->add('result','验证码不正确');

            return back()->withErrors($error);
        }
        $adminUser = User::where('user_name',$loginRequest->get('user_name'))->where('role_id', '>', 0)->first();

        if(empty($adminUser)){

            $error->add('result','用户无后台权限');

            return back()->withErrors($error);
        }else{

            if (md5($loginRequest->get('password'))===$adminUser->password&&$adminUser->role_id){

                Auth::login($adminUser);
                Session::put('admincaptcha', "");
                $this->dispatch(
                    new OperationLogCommand('登录了后台','User','id:'.$adminUser->id)
                );

                return redirect()->route('admin.home');

            }else{
                $error->add('result','用户名或密码错误');

                return back()->withErrors($error);
            }
        }
    }

    public function destroy($id){
        $this->dispatch(
            new OperationLogCommand('退出了后台','User','id:'.$id)
        );
        Auth::logout();
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function captcha($tmp,CaptchaBuilder $builder)
    {
        //图片效果设置样放在 build 方法前面
        $builder->setMaxBehindLines(2);                 //背景干扰线
        $builder->setMaxFrontLines(0);                  //前置干扰线
        $builder->setMaxOffset(6);                      //设置偏移值
        $builder->setDistortion(false);                //是否失真

        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 38, $font = null);

        //获取验证码的内容
        $phrase = $builder->getPhrase();
        //把内容存入session
        Session::put('admincaptcha', $phrase);
        //Session::flash('admincaptcha', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
        $builder->inline();
    }


}
